import { useEffect } from "react";
import { Text, View, ScrollView } from "react-native";
import { sqlh, TestSqliteType } from "@/sqlite/test";
import Btn from "@/components/Btn";
import globalMethods from "@/GlobalMethodProvider";
import RNFS from "react-native-fs";
import { openDatabase, enablePromise, DEBUG } from "react-native-sqlite-storage";
import dayjs from "dayjs";

/** 开启 Promise 返回值操作 */
enablePromise(true);

const SqliteTest = () => {
  useEffect(() => {
    if (!sqlh) {
      globalMethods.$error("sqlite 未初始化成功");
    }
  }, []);

  return (
    <ScrollView style={{ flex: 1 }}>
      <Text style={{ textAlign: "center", fontSize: 24, marginBottom: 20 }}>sqlite数据库测试</Text>
      <View style={{ gap: 20, flexDirection: "row", flexWrap: "wrap", padding: 10 }}>
        <Btn
          text="创建数据库"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .createTable()
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="插入数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .insert<TestSqliteType>({
                  name: "张三",
                  age: 18,
                  height: 180.5,
                  createTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
                })
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="插入多条数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              const createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
              sqlh
                .inserts<Partial<TestSqliteType>[]>([
                  { name: "刘一", age: 1, createTime },
                  { name: "陈二", age: 2, createTime },
                  { name: "张三", age: 3, createTime },
                  { name: "李四", age: 4, height: 12.4, weight: 1.1, createTime },
                  { name: "王五", age: 5, createTime },
                  { name: "赵六", age: 6, createTime },
                  { name: "孙七", age: 7, createTime },
                  { name: "周八", age: 8, height: 180.5, weight: 150.5, createTime },
                  { name: "吴九", age: 9, height: 180.5, weight: 150.5, createTime },
                  { name: "郑十", age: 10, createTime }
                ])
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="表信息"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .tableInfo()
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="所有表信息"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .allTableInfo()
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="获取所有的数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .getList<TestSqliteType[]>()
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="获取所有的数据(只显示部分字段)"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .getList<TestSqliteType[]>("name, age, id")
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="获取 主键(isKey) = 1 的数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .getById<TestSqliteType>(1)
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="获取 name=张三 OR age=3 的数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .getByCustom<TestSqliteType>({ name: "张三", age: 3 }, "OR")
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="更新 主键(isKey) = 1 的数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .updateById<TestSqliteType>({ id: 1, name: "修改后的名字", age: 999 })
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="When子句更新"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .updataByWhen<{ name: string; age: number }>({
                  datas: [
                    { name: "刘一", age: 1 },
                    { name: "陈二", age: 2 },
                    { name: "张三", age: 3 }
                  ],
                  onceMaxUpdateDataLength: 500,
                  fieldOpts: [
                    {
                      setField: "name",
                      getWhenField() {
                        return "name";
                      },
                      getWhenValue(row) {
                        return row.name;
                      },
                      getThenValue(row) {
                        return `${row.name} ${row.age} 岁`;
                      }
                    }
                  ],
                  getExtraUpdateWhen(updates) {
                    return "height = CASE WHEN 1=1 THEN 180 END";
                  },
                  getExtraWhere(updates) {
                    // return `name="刘一" OR name="陈二" OR name="张三"`;
                    return updates.map(e => `name="${e.name}"`).join(" OR ");
                  }
                })
                .then(updateWhenRes => {
                  console.log("updateWhenRes: ", updateWhenRes);
                  const rowsAffected = updateWhenRes.reduce((pre, cur) => {
                    return cur.rowsAffected + pre;
                  }, 0);
                  globalMethods.$success(`操作成功, 完成同步${rowsAffected}条数据`);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="删除 主键(isKey) = 2 的数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .deleteById(2)
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="删除 height=180.5 AND weight=150.5 的数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              sqlh
                .deleteByCustom<TestSqliteType>({ height: 180.5, weight: 150.5 }, "AND")
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="新增单个字段"
          type="success"
          onClick={() => {
            if (sqlh) {
              sqlh
                .addColumn({ field: "hello", type: "TEXT" })
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="新增多个字段"
          type="success"
          onClick={() => {
            if (sqlh) {
              sqlh
                .addColumns([
                  { field: "aaa", type: "TEXT" },
                  { field: "bbb", type: "TEXT" },
                  { field: "ccc", type: "TEXT" }
                ])
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="删除单个字段"
          type="warning"
          onClick={() => {
            if (sqlh) {
              sqlh
                .deleteColumn("hello")
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="清空数据"
          type="warning"
          onClick={() => {
            if (sqlh) {
              sqlh
                .clearTable()
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="删除表"
          type="danger"
          onClick={() => {
            if (sqlh) {
              sqlh
                .deleteTable()
                .then(res => {
                  console.log("res: ", res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="自定义sql"
          type="primary"
          onClick={() => {
            if (sqlh) {
              const sql = `SELECT * FROM sqlite_master`;
              sqlh
                .executeSql(sql)
                .then(res => {
                  const _res = sqlh?.buildRet(res);
                  console.log("_res: ", _res);
                })
                .catch(err => {
                  console.log("err: ", err);
                });
            }
          }}
        />
        <Btn
          text="最后保存的数据"
          type="primary"
          onClick={() => {
            if (sqlh) {
              const maxCreateTimeSql = `SELECT * FROM "test.db" WHERE createTime=(SELECT MAX(createTime) FROM 'test.db')`;
              sqlh.executeSql(maxCreateTimeSql).then(maxCreateTimeRes => {
                const maxCreateTimeDta = sqlh?.buildRet<TestSqliteType[]>(maxCreateTimeRes);
                console.log("本地最后保存的数据: ", maxCreateTimeDta);
              });
            }
          }}
        />
        <Btn
          text="加载数据库文件"
          type="primary"
          onClick={async () => {
            try {
              if (sqlh) {
                console.log("RNFS: ", RNFS);
                const dbPath = `${RNFS.DocumentDirectoryPath}/import_db_file.db`;
                // const dbPath = `${RNFS.DocumentDirectoryPath}/import_db_file.sqlite`;

                const isExists = await RNFS.exists(dbPath);
                if (!isExists) {
                  globalMethods.$warning("没有这个数据库文件: " + dbPath);
                  return;
                }

                /** 开启SQLinte 官方debug */
                DEBUG(true);

                const db = await openDatabase({
                  name: "importDB",
                  readOnly: true,
                  createFromLocation: dbPath,
                  location: "Documents"
                });
                console.log("db: ", db);
                const results = await db.executeSql(`SELECT * FROM "${db.dbName}"`);
                console.log("results: ", results);
                const list = sqlh.buildRet(results);
                console.log("导入的数据数据: ", list);
              }
            } catch (err) {
              console.log("err: ", err);
              globalMethods.$error("导入数据库文件失败");
            } finally {
              DEBUG(false);
            }
          }}
        />
      </View>
    </ScrollView>
  );
};

export default SqliteTest;
